<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use OT\DataDictionary;
use Home\Controller\AlipayController;
header("Content-type: text/html; charset=utf-8");
/**
 * 课程代购控制器
 */
class PurchasingController extends HomeController
{

    /**
     * 检测是否登录
     * */
    public function _initialize()
    {
        if(empty(session('user_id'))){
            header('Location: ' . U('/Home/Login/Login'));exit;
        }else{
            //再来判断权限
            if(session('Supertube')==1){
                //超管 拥有所有权限
            }else{
                $id=session('user_id');//不是超管的时候 user_id是account_number的主键ID
                $jurisdiction=M('account_number')->where("id=$id")->getField('jurisdiction');
                $action_name=ACTION_NAME;
                if($action_name == purchasingAgentList || $action_name == PurchasingAgentList){
                    //访问数据统计
                    $domain = strstr($jurisdiction, ',22,');
                    if(!$domain){
                        $this->error('没有访问权限');
                    }
                }
            }
        }
    }

    /**
     * Mr.Jiang
     * 代购记录
     */
    public function purchasingAgentList()
    {
        $iid = session('iid');
        $pa_id = session('user_id');
        $map['a.iid'] = array('eq',$iid);
        $map['a.pa_id'] = array('eq',$pa_id);
        if($_REQUEST['id_card'] != ''){
            $map['b.id_card'] = array('like','%'.$_REQUEST['id_card'].'%');
            $this->assign('id_card',$_REQUEST['id_card']);
        }
        if(!empty($_REQUEST['start_time']) && !empty($_REQUEST['end_time'])){
            $map['a.create_time'] = array(array('egt',strtotime($_REQUEST['start_time'])),array('elt',strtotime($_REQUEST['end_time']." 23:59:59")));
            $this->assign('start_time',$_REQUEST['start_time']);
            $this->assign('end_time',$_REQUEST['end_time']);
        }else {
            if(!empty($_REQUEST['start_time'])){
                $map['a.create_time'] = array('egt',strtotime($_REQUEST['start_time']));
                $this->assign('start_time',$_REQUEST['start_time']);
            }
            if(!empty($_REQUEST['end_time'])){
                $map['a.create_time'] = array('egt',strtotime($_REQUEST['end_time'].' 23:59:59'));
                $this->assign('end_time',$_REQUEST['end_time']);
            }
        }
        $count = M('order a')->join('left join teach_ucenter_member b on a.uid = b.id')->join('left join teach_vice_order c on a.id = c.order_id')->where($map)->count();
        $Page = new \Think\Page($count, 10, array('id_card'=>$_REQUEST['id_card'],'start_time'=>$_REQUEST['start_time'],'end_time'=>$_REQUEST['end_time']));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $list = M('order a')->field('a.*,b.username,b.id_card,b.id_account,c.name')->join('left join teach_ucenter_member b on a.uid = b.id')->join('left join teach_vice_order c on a.id = c.order_id')->where($map)->limit($Page->firstRow . ',' . $Page->listRows)->order('a.id desc')->select();

        $this->assign('_list', $list);
        $show = $Page->show();// 分页显示输出
        $this->assign("_page", $show);

        $this->assign('cur','代购记录');
        $this->display();
    }

    /**
     * Mr.Jiang
     * 添加代购
     */
    public function addPurchasingAgent()
    {
        $iid = session("iid");
        if(IS_POST){
            $data['iid'] = $iid;
            $data['pa_id'] = session('user_id');
            $id_card = $_REQUEST['id_card'];//身份证号
            // print_r($id_card);die;
            $id_account = $_REQUEST['id_account'];//id账号

            $course_id = $_REQUEST['to_id'];
            $course_type = $_REQUEST['course_type'];//课程类型（1直播，2面授，3在线）
            if($course_type == 1){
                $course_type = 2;
            }else if($course_type == 2){
                $course_type = 3;
            }else {
                $course_type = 1;
            }
            $course_price = $_REQUEST['course_price'];
            $pay_type = $_REQUEST['pay_type'];

            $order_sn = "";
            if($course_type == 1){
                $order_sn = 'ZB';
                $course = D('live_course')->where(array('id'=>$course_id))->find();
            }else if($course_type == 2){
                $order_sn = 'MS';
                $course = D('face_course')->where(array('id'=>$course_id))->find();
            }else {
                $order_sn = 'ZX';
                $course = D('video_course')->where(array('id'=>$course_id))->find();
            }

            $order_sn = $order_sn.date('Ymd',time()).rand(1000,9999);

            if($id_card == ''){
                $this->error("请输入身份证号");
            }

            if(empty($course_id)){
                $this->error("请选择课程");
            }

            $member = D('ucenter_member')->where(array('id_card'=>$id_card))->find();
            $data['uid'] = $member['id'];

            $data['order_sn'] = $order_sn;
            $data['pay_order_sn'] = $order_sn;
            $data['pay_price'] = $course_price;
            $data['type'] = $course_type;
            $data['pay_type'] = $pay_type;

            $time = time();
            $data['update_time'] = $time;
            $data['create_time'] = $time;

            $data['is_pay']=1;//先默认支付成功 待评价
            $data['status']=3;//先默认支付成功 待评价

            $order_id = D('order')->add($data);
            if($order_id){
                $vice_order_data['order_id'] = $order_id;
                $vice_order_data['to_id'] = $course_id;
                $vice_order_data['img'] = $course['img'];
                $vice_order_data['name'] = $course['name'];
                if($course_type == 2){
                    $vice_order_data['live_open_time'] = $course['live_time'];
                }else if($course_type == 3){
                    //$vice_order_data['expire_time'] = $course['live_time'];
                }
                $vice_order_data['old_price'] = $course_price;
                $vice_order_data['price'] = $course_price;
                $vice_order_data['update_time'] = $time;
                $vice_order_data['create_time'] = $time;
                D('vice_order')->add($vice_order_data);

                if($id_account != ''){
                    D('ucenter_member')->where(array('id_card'=>$id_card))->save(array('id_account'=>$id_account));
                }
                if(session('Supertube')==2){
                    //不记录超管的 只记录这种有权限的
                    $data['account_id']=session('user_id');
                    $data['create_time']=time();
                    $data['ip_address']=$_SERVER["REMOTE_ADDR"];
                    $data['content']='代购记录'.'-'.'新增代购';
                    M('account_log')->add($data);
                }
                $this->success('添加代购成功',U('purchasingAgentList'));
            }else {
                $this->error("添加代购失败");
            }
        }else {
            //父级分类
            $parent = D('face_course_type')->where(array('pid' => 0))->order('id desc')->select();
            //子级分类
            $child = D('face_course_type')->where(array('pid' => $parent[0]['id']))->order('id desc')->select();
            //课程
            $course = D('face_course')->where(array('iid' => $iid, 'one_type_id' => $parent[0]['id'], 'two_type_id' => $child[0]['id']))->order('id desc')->select();
            foreach ($course as $key=>$item) {
                $img_path = D('picture')->where(array('id'=>$item['img']))->getField('path');
                $course[$key]['img_path'] = $img_path?$img_path:'';
            }


            $this->assign('parent',$parent);
            $this->assign('child',$child);
            $this->assign('course',$course);
            $this->assign('cur','代购记录');
            $this->display();
        }
    }


    public function pay_z(){
        // print_r($_POST);die;
            $data['iid'] = session('iid');
            $data['pa_id'] = session('user_id');
            $id_card = $_REQUEST['id_card'];//身份证号
            // print_r($id_card);die;
            $id_account = $_REQUEST['id_account'];//id账号

            $course_id = $_REQUEST['to_id'];
            $course_type = $_REQUEST['course_type'];//课程类型（1直播，2面授，3在线）
            if($course_type == 1){
                $course_type = 2;
            }else if($course_type == 2){
                $course_type = 3;
            }else {
                $course_type = 1;
            }
            $course_price = $_REQUEST['course_price'];
            $pay_type = $_REQUEST['pay_type'];

            $order_sn = "";
            if($course_type == 1){
                $order_sn = 'ZB';
                $course = D('live_course')->where(array('id'=>$course_id))->find();
            }else if($course_type == 2){
                $order_sn = 'MS';
                $course = D('face_course')->where(array('id'=>$course_id))->find();
            }else {
                $order_sn = 'ZX';
                $course = D('video_course')->where(array('id'=>$course_id))->find();
            }

            $order_sn = $order_sn.date('Ymd',time()).rand(1000,9999);

            if($id_card == ''){
                // $this->error("请输入身份证号");
                $value=['code'=>'200','msg'=>'请输入身份证号'];
                exit(json_encode($value));
            }

            if(empty($course_id)){
                // $this->error("请选择课程");
                $value=['code'=>'200','msg'=>'请选择课程'];
                exit(json_encode($value));
            }

            $member = D('ucenter_member')->where(array('id_card'=>$id_card))->find();
            $data['uid'] = $member['id'];

            $data['order_sn'] = $order_sn;
            $data['pay_order_sn'] = $order_sn;
            $data['pay_price'] = $course_price;
            $data['type'] = $course_type;
            $data['pay_type'] = $pay_type;

            $time = time();
            $data['update_time'] = $time;
            $data['create_time'] = $time;

            $data['is_pay']=1;//先默认支付成功 待评价
            $data['status']=3;//先默认支付成功 待评价

            $order_id = D('order')->add($data);
            if($order_id){
                $vice_order_data['order_id'] = $order_id;
                $vice_order_data['to_id'] = $course_id;
                $vice_order_data['img'] = $course['img'];
                $vice_order_data['name'] = $course['name'];
                if($course_type == 2){
                    $vice_order_data['live_open_time'] = $course['live_time'];
                }else if($course_type == 3){
                    //$vice_order_data['expire_time'] = $course['live_time'];
                }
                $vice_order_data['old_price'] = $course_price;
                $vice_order_data['price'] = $course_price;
                $vice_order_data['update_time'] = $time;
                $vice_order_data['create_time'] = $time;
                D('vice_order')->add($vice_order_data);

                if($id_account != ''){
                    D('ucenter_member')->where(array('id_card'=>$id_card))->save(array('id_account'=>$id_account));
                }


                //这里我要唤醒支付宝 H5支付
                $alipay=A('Alipay');
                $inf=file_get_contents($alipay);
                print_r($inf);die;
                if(session('Supertube')==2){
                    //不记录超管的 只记录这种有权限的
                    $data['account_id']=session('user_id');
                    $data['create_time']=time();
                    $data['ip_address']=$_SERVER["REMOTE_ADDR"];
                    $data['content']='代购记录'.'-'.'新增代购';
                    M('account_log')->add($data);
                }
                $this->success('添加代购成功',U('purchasingAgentList'));
            }else {
                $this->error("添加代购失败");
            }
    }

    //现在的需求是聚合支付
    public function aggregate_payment(){
            $data['iid'] = session('iid');
            $data['pa_id'] = session('user_id');
            $id_card = $_REQUEST['id_card'];//身份证号
            // print_r($id_card);die;
            $id_account = $_REQUEST['id_account'];//id账号

            $course_id = $_REQUEST['to_id'];
            $course_type = $_REQUEST['course_type'];//课程类型（1直播，2面授，3在线）
            if($course_type == 1){
                $course_type = 2;
            }else if($course_type == 2){
                $course_type = 3;
            }else {
                $course_type = 1;
            }
            $course_price = $_REQUEST['course_price'];
            $pay_type = $_REQUEST['pay_type'];

            $order_sn = "";
            if($course_type == 1){
                $order_sn = 'ZB';
                $course = D('live_course')->where(array('id'=>$course_id))->find();
            }else if($course_type == 2){
                $order_sn = 'MS';
                $course = D('face_course')->where(array('id'=>$course_id))->find();
            }else {
                $order_sn = 'ZX';
                $course = D('video_course')->where(array('id'=>$course_id))->find();
            }

            $order_sn = $order_sn.date('Ymd',time()).rand(1000,9999);

            if($id_card == ''){
                // $this->error("请输入身份证号");
                $value=['code'=>'200','msg'=>'请输入身份证号'];
                exit(json_encode($value));
            }

            if(empty($course_id)){
                // $this->error("请选择课程");
                $value=['code'=>'200','msg'=>'请选择课程'];
                exit(json_encode($value));
            }

            $member = D('ucenter_member')->where(array('id_card'=>$id_card))->find();
            $data['uid'] = $member['id'];

            $data['order_sn'] = $order_sn;
            $data['pay_order_sn'] = $order_sn;
            $data['pay_price'] = $course_price;
            $data['type'] = $course_type;
            $data['pay_type'] = $pay_type;

            $time = time();
            $data['update_time'] = $time;
            $data['create_time'] = $time;

            // $data['is_pay']=1;//先默认支付成功 待评价
            // $data['status']=3;//先默认支付成功 待评价

            $order_id = D('order')->add($data);
            if($order_id){
                $vice_order_data['order_id'] = $order_id;
                $vice_order_data['to_id'] = $course_id;
                $vice_order_data['img'] = $course['img'];
                $vice_order_data['name'] = $course['name'];
                if($course_type == 2){
                    $vice_order_data['live_open_time'] = $course['live_time'];
                }else if($course_type == 3){
                    //$vice_order_data['expire_time'] = $course['live_time'];
                }
                $vice_order_data['old_price'] = $course_price;
                $vice_order_data['price'] = $course_price;
                $vice_order_data['update_time'] = $time;
                $vice_order_data['create_time'] = $time;
                D('vice_order')->add($vice_order_data);

                if($id_account != ''){
                    D('ucenter_member')->where(array('id_card'=>$id_card))->save(array('id_account'=>$id_account));
                }


                //这里我要唤醒支付宝 H5支付
                $add_data['order_sn']=$data['order_sn'];//订单号
                $add_data['amount']=$course_price*100;//金额 分  

                Vendor('pay.pay');
                $obj = new \pay;

                $recceivers = getRecceivers($order_id);
                $payment_info = $obj->payment_info($add_data,$recceivers);
                $qrc=json_decode($payment_info['data']['credential'],true);
                $gg=$qrc['qr_code'];
                
                $this->qrcode($gg,$data['order_sn']);


                if(session('Supertube')==2){
                    //不记录超管的 只记录这种有权限的
                    $data['account_id']=session('user_id');
                    $data['create_time']=time();
                    $data['ip_address']=$_SERVER["REMOTE_ADDR"];
                    $data['content']='代购记录'.'-'.'新增代购';
                    M('account_log')->add($data);
                }

                $img_info="http://".$_SERVER['HTTP_HOST'].'/Public/Home/images/ttt/'.$order_sn.'.png';
     
                $value=['code'=>'100','msg'=>'成功','info'=>$img_info];
                exit(json_encode($value));

            }else {
                $value=['code'=>'200','msg'=>'失败'];
                exit(json_encode($value));
            }
    }


    public function qrcode($text,$order_sn){ 
        $matrixPointSize = 12;
        $errorCorrectionLevel = 'L';
        $outfile='Public/Home/images/ttt/'.$order_sn.'.png';
        Vendor('qr_code');
        $objj = new \Qrcode;
        return $objj->png($text,$outfile,$errorCorrectionLevel,$matrixPointSize,1);
    }

    //立即支付
    public function pay_order(){
        $id=$_POST['id'];
        $order_sn=M('order')->where("id=$id")->getField('order_sn');
        $img_info="http://".$_SERVER['HTTP_HOST'].'/Public/Home/images/ttt/'.$order_sn.'.png';
        $value=['code'=>'100','msg'=>'成功','info'=>$img_info];
        exit(json_encode($value));
    }

    /**
     * Mr.Jiang
     * 删除代购
     */
    public function delPurchasingAgent()
    {
        $id = $_REQUEST['id'];
        $count = M('order')->where(array('id'=>$id))->count();
        if($count <= 0){
            $this->error("代购记录不存在或已被删除");
        }

        $result = D('order')->where(array('id'=>$id))->delete();
        if($result){
            D('vice_order')->where(array('order_id'=>$id))->delete();
            if(session('Supertube')==2){
                //不记录超管的 只记录这种有权限的
                $data['account_id']=session('user_id');
                $data['create_time']=time();
                $data['ip_address']=$_SERVER["REMOTE_ADDR"];
                $data['content']='代购记录'.'-'.'删除代购';
                M('account_log')->add($data);
            }
            $this->success("删除成功");
        }else {
            $this->error("删除失败");
        }
    }

    /**
     * Mr.Jiang
     * 根据身份证获取学生列表
     */
    public function getStudentsList()
    {
        $id_card = $_REQUEST['id_card'];
        $map['user_type'] = array('eq',2);
        $map['id_card'] = array('like','%'.$id_card.'%');
        $list = D('ucenter_member')->where($map)->select();
        $list = $list ? $list : [];
        return api_return(1, '信息获取成功', $list);
    }

    /**
     * Mr.Jiang
     * 根据类别获得分类
     */
    public function getType()
    {
        $category = $_REQUEST['category'];//1面授，2点播，3直播
        if ($category == 1) {
            $parent = D('face_course_type')->where(array('pid' => 0))->order('id desc')->select();
            $child = D('face_course_type')->where(array('pid' => $parent[0]['id']))->order('id desc')->select();
        } else if ($category == 2) {
            $parent = D('video_course_type')->where(array('pid' => 0))->order('id desc')->select();
            $child = D('video_course_type')->where(array('pid' => $parent[0]['id']))->order('id desc')->select();
        } else {
            $parent = D('live_course_type')->where(array('pid' => 0))->order('id desc')->select();
            $child = D('live_course_type')->where(array('pid' => $parent[0]['id']))->order('id desc')->select();
        }
        $data['parent'] = $parent ? $parent : [];
        $data['child'] = $child ? $child : [];
        return api_return(1, '信息获取成功', $data);
    }

    /**
     * Mr.Jiang
     * 根据类别与父类获得子类
     */
    public function getChildType()
    {
        $category = $_REQUEST['category'];//1面授，2点播，3直播
        $pid = $_REQUEST['pid'];
        if ($category == 1) {
            $child = D('face_course_type')->where(array('pid' => $pid))->order('id desc')->select();
        } else if ($category == 2) {
            $child = D('video_course_type')->where(array('pid' => $pid))->order('id desc')->select();
        } else {
            $child = D('live_course_type')->where(array('pid' => $pid))->order('id desc')->select();
        }

        return api_return(1, '信息获取成功', $child);
    }

    /**
     * Mr.Jiang
     * 根据类别与分类获取课程
     */
    public function getCourse()
    {
        $name = $_REQUEST['name'];//课程名称
        $category = $_REQUEST['category'];//1面授，2点播，3直播
        $one_type_id = $_REQUEST['one_type_id'];
        $two_type_id = $_REQUEST['two_type_id'];
        $iid = session('iid');//机构ID

        $map['iid'] = array('eq',$iid);
        $map['one_type_id'] = array('eq',$one_type_id);
        $map['two_type_id'] = array('eq',$two_type_id);
        if($name != ''){
            $map['name'] = array('like','%'.$name.'%');
        }
        if ($category == 1) {
            $course = D('face_course')->where($map)->order('id desc')->select();
        } else if ($category == 2) {
            $course = D('video_course')->where($map)->order('id desc')->select();
        } else {
            $course = D('live_course')->where($map)->order('id desc')->select();
        }
        foreach ($course as $key=>$item){
            $img_path = D('picture')->where(array('id'=>$item['img']))->getField('path');
            $course[$key]['img_path'] = $img_path?$img_path:'';
        }
        $course = $course?$course:[];
        return api_return(1, '信息获取成功', $course);
    }
}
